package com.kb.erp.service.impl;


import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.kb.erp.entity.CRMSalesOrder;
import com.kb.erp.entity.DbErrorLog;
import com.kb.erp.entity.FlowChartQueue;
import com.kb.erp.mapper.sqlServer.CommonMapper;
import com.kb.erp.mapper.sqlServer.DbErrorLogMapper;
import com.kb.erp.service.CommonService;
import com.kb.erp.service.CrmService;
import com.kb.erp.util.MessageUtil;
import com.xxl.job.core.context.XxlJobHelper;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.Objects;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@Service
@DS("slave-1")
public class CommonServiceImpl extends ServiceImpl<CommonMapper,FlowChartQueue> implements CommonService {
    @Resource
    private CommonMapper commonMapper;
    @Resource
    private DbErrorLogMapper dbErrorLogMapper;
    @Resource
    private CrmService crmService;


    @Override
    public void updateStatus() {
        LambdaQueryWrapper<FlowChartQueue> queryWrapper = Wrappers.lambdaQuery();


        // 获取当前时间
        LocalDateTime currentDateTime = LocalDateTime.now();
        // 获取两天前的日期
        LocalDateTime twoDaysAgo = currentDateTime.minusDays(2);
        // 将日期格式化为字符串
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        String formattedTwoDaysAgo = twoDaysAgo.format(formatter);


        queryWrapper.eq(FlowChartQueue::getFStatus,2).like(FlowChartQueue::getFData,"\"formTitle\":\"电子领料_").gt(FlowChartQueue::getFCreateDate,formattedTwoDaysAgo);
        List<FlowChartQueue> flowChartQueues = commonMapper.selectList(queryWrapper);
        XxlJobHelper.log("查询到可更新数量："+flowChartQueues.size());

        if (CollectionUtils.isNotEmpty(flowChartQueues)){
            for (FlowChartQueue chartQueue : flowChartQueues) {
                LambdaQueryWrapper<FlowChartQueue> update = Wrappers.lambdaQuery();
                update.eq(FlowChartQueue::getFID,chartQueue.getFID());
                chartQueue.setFStatus(0);
                System.out.println(chartQueue.getFID());
                XxlJobHelper.log("更新状态的id："+chartQueue.getFID());
                this.update(chartQueue,update);

            }
        }

    }

    @Override
    public void erp2crmBySalesOrder() {
        QueryWrapper<DbErrorLog> queryWrapper = new QueryWrapper<>();
        queryWrapper.orderByDesc("RKEY");
        queryWrapper.eq("errcode", "SO_ERP2CRM");
        Page<DbErrorLog> page = new Page<>(1, 10);

        // 查询数据
        Page<DbErrorLog> resultPage = dbErrorLogMapper.selectPage(page, queryWrapper);

        // 获取结果列表
        List<DbErrorLog> errorLogs = resultPage.getRecords();
        if (CollectionUtil.isNotEmpty(errorLogs)){
            DbErrorLog errorLog = errorLogs.get(0);
            LocalDateTime errTime = errorLog.getErrtime();
            // 获取当前日期
            LocalDate today = LocalDate.now();
            // 从 LocalDateTime 中提取日期部分
            LocalDate date = errTime.toLocalDate();
            // 比较日期部分
            boolean equals = date.equals(today);
            if (equals){
                //是今天发生的错误
                MessageUtil.sentMessage("23988",errorLog.getErrmsg(),"ERP同步CRM订单数据出现异常");
                //删除存在的唯一键
                String errmsg = errorLog.getErrmsg();
                if (errmsg.contains("dbo.CRM_SalesOrder”中插入重复键的行。重复键值为")){
                    // 定义正则表达式，用于匹配括号内的内容
                    String regex = "\\(([^)]+)\\)";
                    Pattern pattern = Pattern.compile(regex);
                    Matcher matcher = pattern.matcher(errmsg);
                    if (matcher.find()) {
                        String duplicateKey = matcher.group(1);
                        //为了安全 先查询crm数据库 并且只有一天才删除
                        List<CRMSalesOrder> crmSalesOrderList = crmService.querySalesOrder(duplicateKey);
                        if (Objects.equals(crmSalesOrderList.size(),1)){
                            int del = crmService.del(duplicateKey);
                            if (Objects.equals(del,1)){
                                MessageUtil.sentMessage("23988",duplicateKey,"删除CRM销售订单成功");
                            }
                        }
                    }
                }
            }
        }
    }

}
